<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $params = $request->only('name','status','type','parent_id');
        if(empty($params['type'])){
//            $params['type'] = 1;
        }
        $res = Category::getQueryData($params);
        $res['options']['categories'] = Category::query()->select('id','name')
            ->whereNull('parent_id')
            ->orderBy('sort', 'asc')
            ->get();
        return apiResponse(data: $res);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|min:2|max:255|unique:categories,name',
            'description' => 'nullable|string',
            'icon' => 'nullable|string|max:255',
            'parent_id' => 'nullable|exists:categories,id',
            'sort' => 'nullable|integer',
        ]);
        $category = Category::create($request->all());
        return apiResponse(data: $category);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Category $category)
    {
        $validated = $request->validate([
            'name' => [
                'nullable',
                'string',
                'max:255',
                'min:2',
                Rule::unique('categories')->ignore($category->id), // 忽略当前分类的 ID
            ],
            'icon' => 'nullable|string|max:255',
            'description' => 'nullable|string',
            'sort' => 'nullable|integer',
            'parent_id' => 'nullable|exists:categories,id|not_in:'.$category->id,
        ]);
        $category->update($request->all());
        return apiResponse(data: $category);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $ids)
    {
        $idsArr = explode(',', $ids);
        $deletedCount = Category::destroy($idsArr);
        return apiResponse(data: ['deleted_count' => $deletedCount]);
    }
}
